<template>
  <div>
    <table cellspacing="0" class="table">
      <thead>
        <tr>
          <th width="50">
            <Checkbox v-model="selectAll" @on-change="onSelectAll"></Checkbox>
          </th>
          <th width="20"></th>
          <th v-for="item in listData" :key="item.id" :width="item.width">
            <Dropdown @on-click="onBatchSet({setType: item.key, type: type})"> 
              <span>{{item.title}}</span> 
              <Icon v-if="item.key == '0' || item.key == '1' || item.key == '2' || item.key == '3' || item.key == '4'" class="cursor-title" type="ios-cog" />
              <DropdownMenu   slot="list"  v-if="item.key == '0' || item.key == '1' || item.key == '2' || item.key == '3' || item.key == '4'" class="cursor-title" type="ios-cog">
                <DropdownItem  >批量设置{{item.title}}</DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </th>
        </tr>
      </thead>
      <tbody v-for="(item, index) in viewData" :key="index">
        <tr>
          <td>
            <Checkbox v-model="item.checked" @on-change="onJoinSaleCheck(item)"></Checkbox>
          </td>
          <td class="cursor-title">
            <Icon
              type="ios-arrow-down"
              size="20"
              v-if="item.showChildren"
              @click="onShowChild(item)"
            ></Icon>
            <Icon
              type="ios-arrow-forward"
              size="20"
              v-if="item.productSkuList && item.productSkuList.length && !item.showChildren"
              @click="onShowChild(item)"
            ></Icon>
          </td>
          <td :title="item.code">{{item.code}}</td>
          <td>-</td>
          <td  class="cursor-title" :title="item.title">
            <div class=" flex-start">
              <!-- <img :src="$store.state.moreSale.imgSrc+item.productPrimaryImg+'_90w'" alt> -->
              <span class="e2">{{item.title ? item.title : '-'}}</span>
            </div>
          </td>
          <td>
            <Input @on-keyup="onTestValue(item, 'giftPoint')"   @on-blur="onSetgiftPoint(item)" :min="0" style="width:60px;" maxlength="4" :max="999" v-model="item.giftPoint" />
          </td>
          <td>
            <Input   @on-blur="onSetGiftRebate(item)" class="w40" style="width:60px;" maxlength="5"  v-model="item.giftRebate"/>
          </td>
          <td>
            <Select v-model="item.giftCouponId" filterable style="width:60px" @on-change="onSetgiftCouponId(item)" transfer="true">
                <Option v-for="item in bargainCouponsData" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </td>
          <td>
            <Input @on-keyup="onTestValue(item, 'sellOutQuantity')" class="w40" style="width:60px;" @on-blur="onSetsellOutQuantity(item)" maxlength="6"  v-model="item.sellOutQuantity"/>
          </td>
          <!-- <td>
            <Input class="w40" style="width:60px;" @on-blur="onSetWarningQuantity(item)" maxlength="4"  v-model="item.warningQuantity"/>
          </td> -->
          <td>
            <Input  class="w40" maxlength="5" style="width:60px" @on-blur="onSetSale(item)"  v-model="item.sale"/>
          </td>
          <td>
            <Button size="small" @click="onDeleteSale(index,list)">删除</Button>
          </td>
        </tr>
        <template  v-if="item.productSkuList && item.productSkuList.length">
          <tr
            v-for="(child, index1) in item.productSkuList"
            :key="index1"
            v-show="item.showChildren"
          >
            <td></td>
            <td></td>
            <td>
              <Checkbox v-model="child.checked" @on-change="onJoinSaleCheck(child,item)"></Checkbox>
            </td>
            <td :title="child.code">{{child.code}}</td>
            <td  :title="child.title" class="cursor-title">
              <div class=" flex-start">
                <!-- <img :src="$store.state.moreSale.imgSrc+item.productPrimaryImg+'_90w'" alt> -->
                <span class="e2">{{child.title}}</span>
              </div>
            </td>
          <!-- 积分增加 -->
          <td>
            <Input @on-keyup="onTestValue(child, 'giftPoint')"   @on-blur="onSetgiftPoint(child, item)" :min="0" style="width:60px;" maxlength="4" :max="999" v-model="child.giftPoint" />
          </td>
          <!-- 返利增加 -->
          <td>
            <Input class="w40" style="width:60px;" @on-blur="onSetGiftRebate(child, item)" maxlength="5"  v-model="child.giftRebate"/>
          </td>
          <td>
            <Select v-model="child.giftCouponId" style="width:60px" filterable  filter-by-label @on-change="onSetgiftCouponId(child)" transfer="true">
                <Option v-for="item in bargainCouponsData" :value="item.value"  :key="item.value">{{ item.label }}</Option>
            </Select>
          </td>
          <td>
            <Input @on-keyup="onTestValue(child, 'sellOutQuantity')" class="w40" style="width:60px;" @on-blur="onSetsellOutQuantity(child, item)" maxlength="6"  v-model="child.sellOutQuantity"/>
          </td>
          <!-- <td>
            <Input class="w40" style="width:60px;" @on-blur="onSetWarningQuantity(child, item)" maxlength="4" v-model="child.warningQuantity"/>
          </td> -->
          <td>
            <Input  class="w60" style="width:60px" maxlength="5" @on-blur="onSetSale(child, item)"  v-model="child.sale"/>
          </td>
            <td>
              <Button size="small" @click="onReplenish(child, item)" v-show="child.isReplenish">补货</Button>
              <Button @click="onDeleteSale(index1, item.productSkuList,index,list)" size="small">删除</Button>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
    <Loader  :status="status" @refresh="getData"></Loader>
    <ReplenishItem ref="replenish"></ReplenishItem>
    <SetCoupon ref="editCoupon" ></SetCoupon>
    <BatchSetIntegral ref="editIntegral"></BatchSetIntegral>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import ReplenishItem from '../edit/ReplenishItem'
import SetCoupon from '../edit/BatchSetCouponItem'
import BatchSetIntegral from '../edit/BatchSetIntegralItem'
import {getMinValue, getMaxValue, getSum, onSet} from "@/views/sales/common/TableSaleMethods"
export default {
  components: {
    ReplenishItem,
    SetCoupon,
    BatchSetIntegral
  },
  props: {
    list: "",
    status: "",
    listData: "",
    type: ''
  },
  data() {
    return {
      selectAll: false,
      totalItem: 1,
      pageSize: window.$pageSize,
      currentPage: 1,
      viewData: [],
      id: this.$route.query.id || ''
    };
  },
  created () {
    this.initData()
  },
  methods: {
    initData () {
      this.totalItem = this.list.length;
      this.viewData =  this.list;
    },
    getSum(param, object) {
      return getSum(param, object)
    },
    getMinMaxValue(param, object) {
      if(getMinValue(param, object)==getMaxValue(param, object)) {
        return `[${getMinValue(param, object)}]`
      }else {
        return  `[${getMinValue(param, object)}-${getMaxValue(param, object)}]`;
      }
    },
    onSelectAll() {
      // 全选 、全不选
      this.$emit("onChangeSelectAll", this.selectAll);
    },
    onJoinSale(child, item) {
      this.$emit("onJoinSale", child, item);
    },
    onShowChild(item) {
      item.showChildren = !item.showChildren;
    },
    onJoinSaleCheck(child, item) {
      this.$emit("onJoinSaleCheck", child, item);
    },
    onDeleteSale(index, data, index1, data1) {
      this.$emit("onDeleteSale", index, data, index1, data1);
    },
    onPageChange(val) {
      this.viewData =  this.list.slice(((val-1) * this.pageSize),val * this.pageSize);
    },
    onPageSizeChange(val) {
      this.pageSize= val;
      this.viewData = this.list.slice(0,val)
    },
    onReplenish(item) {
      this.$refs.replenish.reset(item)
    },
    // 商品积分
    onSetgiftPoint(item, child) {
      if((!item['giftPoint'] || !/^([\+ \-]?([1-9]\d*)|(0))([.]\d{0,2})?$/.test(item['giftPoint'])) && item.productSkuList) {
        return 
      }
      this.onNegative(item, 'giftPoint')
      // if (!item.giftPoint) return
      let ids = []
      if (child) {
        ids = [item.acId]
      } else {
        ids = item.productSkuList.map(item=> {
          return item.acId
        })
      }
      this.$store.dispatch('setGiftPoint', {activityId: this.id, ids: ids, giftPoint: item.giftPoint}).then(data => {
        this.$Notice.success({
          title: '温馨提示',
          desc: "商品积分修改成功"
        })
        onSet(item, child, 'giftPoint')
      })
    },
    // 商品返利
    onSetGiftRebate(item, child) {
      if((!item['giftRebate'] || !/^([\+ \-]?([1-9]\d*)|(0))([.]\d{0,2})?$/.test(item['giftRebate'])) && item.productSkuList) {
        return 
      }
      this.onNegative(item, 'giftRebate')
      // if (!item.giftRebate) return
      let ids = []
      if (child) {
        ids = [item.acId]
      } else {
        ids = item.productSkuList.map(item=> {
          return item.acId
        })
      }
      this.$store.dispatch('setGiftRebate', {activityId: this.id, ids: ids, giftRebate: item.giftRebate}).then(data => {
        this.$Notice.success({
          title: '温馨提示',
          desc: "商品返利修改成功"
        })
        onSet(item, child, 'giftRebate')
      })
    },
    // 促销库存
    onSetsellOutQuantity(item, child) {
      // if (!item.sellOutQuantity) return
      if((!item['sellOutQuantity'] || !/^([\+ \-]?([1-9]\d*)|(0))([.]\d{0,2})?$/.test(item['sellOutQuantity'])) && item.productSkuList) {
        return 
      }
      let ids = []
      if (child) {
        ids = [item.acId]
      } else {
        ids = item.productSkuList.map(item=> {
          return item.acId
        })
      }
      this.$store.dispatch('setSellOutQuantity', {activityId: this.id, ids: ids, sellOutQuantity: item.sellOutQuantity}).then(data => {
        this.$Notice.success({
          title: '温馨提示',
          desc: "促销库存修改成功"
        })
        onSet(item, child, 'sellOutQuantity')
      })
    },
    onSetWarningQuantity(item, child) {
      onSet(item, child, 'warningQuantity')
    },
    // 促销价
    onSetSale(item, child) {
      // if (!item.sale) return
      if((!item['sale'] || !/^([\+ \-]?([1-9]\d*)|(0))([.]\d{0,2})?$/.test(item['sale'])) && item.productSkuList) {
        return 
      }
      this.onNegative(item, 'sale')
      let ids = []
      if (child) {
        ids = [item.acId]
      } else {
        ids = item.productSkuList.map(item=> {
          return item.acId
        })
      }
      this.$store.dispatch('setProQuantity', {activityId: this.id, ids: ids, promotionPrice : item.sale}).then(res => {
        this.$Notice.success({
          title: '温馨提示',
          desc: "促销价修改成功"
        })
        onSet(item, child, 'sale')
      })
    },
    // 修改优惠券
    onSetgiftCouponId(data) {
      if (!data.giftCouponId) return
      let ids = []
      if (data.productSkuList && data.productSkuList.length) {
        ids = data.productSkuList.map(item=> {
          return item.acId
        })
      } else {
        ids = [data.acId]
      }
      this.$store.dispatch('setCouponId', {activityId: this.id, ids: ids, giftCouponId: data.giftCouponId == '0' ? '' : data.giftCouponId}).then(res => {
        this.$Notice.success({
          title: '温馨提示',
          desc: "优惠券修改成功"
        })
        if (data.productSkuList && data.productSkuList.length) {
          for (let item of data.productSkuList) {
            item['giftCouponId'] = data['giftCouponId']
          }
        }
      })
    },
    onBatchSet(param) {
      let type = ''
      switch(param.setType) {
        case '0':
          type = 'integral';
        break;
        case '1':
          type = 'rebate'
        break;
        case '2':
          type = ''
        break;
        case '3':
          type = 'sellOutQuantity'
        break;
        case '4':
          type = 'sale'
        break;
      }
      if(type) {
        this.$refs.editIntegral.reset({setType: type, type: param.type})
      } else {
        this.$refs.editCoupon.reset({type: this.type})
      }
    },
    onTestValue(row, type) {
      if((!row[type] || !/^([\+ \-]?([1-9]\d*)|(0))([.]\d{0,2})?$/.test(row[type])) && row.productSkuList) {
        return false;
      }
      let value = JSON.parse(JSON.stringify(row))
      if(!(/^[1-9]\d*$/.test(row[type]))) {
        for (let i=0;  i<row[type].length ;i++) {
          if(!(/^[1-9]\d*$/.test(row[type][i]))) {
            row[type] = row[type].substring(0, i) + row[type].substring(i+1, row[type].length)
          }
        }
      }
    },
    onNegative(row, type) {
      if((!row[type] || !/^([\+ \-]?([1-9]\d*)|(0))([.]\d{0,2})?$/.test(row[type])) && row.productSkuList) {
        return 
      }
      let value = JSON.parse(JSON.stringify(row))
      if(!(/^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)|(0))$/.test(row[type]))) {
        for (let i=0;  i<row[type].length; i++) {
          if(!(/^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)|(0))$/.test(row[type][i]))) {
            row[type] = row[type].substring(0, i) + row[type].substring(i+1, row[type].length)
          }
        }
      }
    }
  },
  computed: {
    ...mapGetters([
      'bargainCouponsData'
    ])
  },
  filters: {
    status(val) {
      if (val) {
        return "上架";
      } else {
        return "下架";
      }
    }
  },
  watch: {
    list () {
      this.initData()
    }
  }
};
</script>

